<?php

namespace App\Wxapp\Controllers;

use App\Store\Models\Basic\GoodsContent;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Order\OrderRecovery;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Models\Order\OrderSales;
use App\Store\Models\Order\OrderSalesGoods;
use Illuminate\Http\Request;


/**
 * 订单相关
 */
class OrderController extends BaseController
{

    /**
     * 订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getlist(Request $request)
    {
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $cp_id = $this->cp_id;
        $mem_id = $this->meminfo['id'];
        $salesList = OrderSales::getListByMem($cp_id, $mem_id);

        foreach ($salesList as &$sales) {
            $sales['type'] = 'sales_order';
        }


        // 纯回收订单
        $recoveryList = OrderRecovery::query()
            ->with(['storeinfo', 'goodslist'])
            ->where(['cp_id' => $cp_id, 'is_del' => 1, 'mem_id' => $mem_id])
            ->where('audit_status', '<>', 3)
            ->get()
            ->toArray();

        foreach ($recoveryList as &$val) {
            $val['type'] = 'recovery_order';
            foreach ($val['goodslist'] as &$v) {
                $v['real_money'] = -abs($v['money']);
            }
        }

        $list = array_merge($salesList, $recoveryList);
        array_multisort(array_column($list, 'create_at'), SORT_DESC, $list);

        $newList = [];
        foreach ($list as $item) {
            $arr = [];
            $arr['id'] = $item['id'];
            $arr['cp_id'] = $item['cp_id'];
            $arr['store_id'] = $item['store_id'];
            $arr['type'] = $item['type'];
            $arr['order_sn'] = $item['order_sn'];
            $arr['mem_id'] = $item['mem_id'];
            $arr['pay_type_name'] = $item['pay_type_name'];
            $arr['order_at'] = $item['order_at'];
            if ($item['type'] == 'sales_order') {
                $arr['total_money'] = $item['total_money'];
                $arr['real_money'] = $item['real_money'];
            } else {
                $arr['total_money'] = '';
                $arr['real_money'] = $item['total_money'];
            }

            $goodsArr = [];
            foreach ($item['goodslist'] as $goods) {
                $goodsArr['id'] = $goods['id'];
                $goodsArr['count'] = $goods['count'];
                $goodsArr['price'] = $goods['price'];
                $goodsArr['weight'] = $goods['weight'];
                $goodsArr['goods_category_id'] = $goods['goods_category_id'];
                $goodsArr['goods_sn_code'] = $goods['goods_sn_code'];
                $goodsArr['is_del'] = $goods['is_del'];
                $goodsArr['order_at'] = $goods['order_at'];
                if ($item['type'] == 'sales_order') {
                    $goodsinfo = json_decode($goods['goodsinfo'], true);
                    $goodsArr['total_money'] = $goods['total_money'];
                    $goodsArr['real_total_money'] = $goods['real_total_money'];
                    $goodsArr['label_price'] = $goods['label_price'];
                    $goodsArr['goods_name'] = $goods['goods_name'];
                    $goodsArr['goods_img'] = $goodsinfo['goods_img'] ?? '';
                } else {
                    $goodsArr['total_money'] = '';
                    $goodsArr['real_total_money'] = $goods['real_money'];
                    $goodsArr['label_price'] = $goods['label_price']??'';
                    $goodsArr['goods_name'] = $goods['goods_catefory_name'];
                    $goodsArr['goods_img'] = '';
                }
                $arr['goods_list'][] = $goodsArr;
            }
            $newList[] = $arr;
        }


        // 计算总记录数
        $total = count($newList);
        // 计算总页数
        $totalPage = ceil($total / $limit);
        // 计算当前页的起始位置
        $offset = ($page - 1) * $limit;
        $currentPageData = array_slice($newList, $offset, $limit);

        $data['list'] = $currentPageData;
        $data['page'] = [
            'totalCount' => count($newList),
            'currentPage' => $page,
            'totalPage' => $totalPage
        ];
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }


    /**
     * 订单详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;

        $info = OrderSales::with(['shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goodslist', 'recoverygoodslist', 'sendgoodslist', 'classessetinfo'])
            ->where(['id' => $id, 'cp_id' => $this->cp_id, 'mem_id' => $this->meminfo['id'], 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }


    /**
     * 电子质保单接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getinfoinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $type = $request->type ?? 'sales_order';
        $order = [];
        $data = [];
        if ($type == 'sales_order') {
            $info = OrderSalesGoods::with(['storeinfo', 'orderinfo', 'shoppingaccountinfo1'])
                ->where(['id' => $id, 'cp_id' => $this->cp_id, 'mem_id' => $this->meminfo['id'], 'is_del' => 1])
                ->first();
            if (empty($info)) {
                return response()->json(['code' => '001', 'msg' => '数据不存在']);
            }
            $info = $info->toArray();


            $cost_price_total = ((($info['cost_price'] - $info['cost_price_discount']) * $info['weight']) + ($info['pieceprice_fee'] * $info['count']));
            $goodsinfo = json_decode($info['goodsinfo'], true);
            $data['total_money'] = $info['total_money'];
            $data['real_total_money'] = $info['money_received']>0?$info['money_received']:$info['real_total_money'];
            $data['label_price'] = $info['label_price'];
            $data['goods_name'] = $info['goods_name'];
            $data['goods_img'] = $goodsinfo['goods_img'] ?? '';
            $data['cf_no'] = $goodsinfo['cf_no'] ?? '';
            $data['cost_price'] = $cost_price_total;
            $data['add_fee'] = $info['add_fee1'] + $info['add_fee2'];
            $data['weight'] = $info['weight'];
            $goods_stock_id = $info['goods_stock_id'] ?? 0;
            $content = '';
            if ($goods_stock_id > 0) {
                $goods_stock = GoodsStockList::query()
                    ->where(['cp_id' => $this->cp_id, 'id' => $goods_stock_id, 'is_del' => 1])
                    ->first();

                $data['cf_no'] = empty($data['cf_no'])?$goods_stock['cf_no']:$data['cf_no'];
                $goods_stock = empty($goods_stock)?[]:$goods_stock->toArray();
                $content=GoodsContent::query()
                    ->where(['cp_id' => $this->cp_id,  'is_del' => 1,'id'=>$goods_stock['goods_content_id']])
                    ->value('content_name')??'';

            }
            $data['content'] = $content;

            $orderinfo = $info['orderinfo'];
            $order['total_money'] = $orderinfo['total_money'];
            $order['real_money'] = $orderinfo['real_money'];

        } else {
            $info = OrderRecoveryGoods::with(['storeinfo', 'orderinfo', 'shoppingaccountinfo1'])
                ->where(['id' => $id, 'cp_id' => $this->cp_id, 'mem_id' => $this->meminfo['id'], 'is_del' => 1])
                ->first();

            if (empty($info)) {
                return response()->json(['code' => '001', 'msg' => '数据不存在']);
            }

            $info = $info->toArray();
            $data['total_money'] = '';
            $data['real_total_money'] = -abs($info['money']);
            $data['label_price'] = $info['d_price'];
            $data['goods_name'] = $info['goods_catefory_name'];
            $data['goods_img'] = '';
            $data['cost_price_total'] = '';
            $data['add_fee'] = '';
            $data['cf_no'] = '';
            $data['content'] = '';
            $data['weight'] = $info['weight'] - $info['loss_weight'];

            $orderinfo = $info['orderinfo'];
            $order['total_money'] = '';
            $order['real_money'] = $orderinfo['total_money'];
        }

        // 商品信息
        $data['id'] = $info['id'];
        $data['count'] = $info['count'];
        $data['price'] = $info['price'];
        $data['balance_money'] = $info['balance_money']?? 0;
        $data['pointstobalance'] = $info['pointstobalance']??0;
        $data['goods_category_id'] = $info['goods_category_id'];
        $data['goods_sn_code'] = $info['goods_sn_code'];
        $data['is_del'] = $info['is_del'];
        $data['order_at'] = $info['order_at'];

        // 订单信息
        $order['id'] = $orderinfo['id'];
        $order['cp_id'] = $orderinfo['cp_id'];
        $order['store_id'] = $orderinfo['store_id'];
        $order['order_sn'] = $orderinfo['order_sn'];
        $order['mem_id'] = $orderinfo['mem_id'];
        $order['pay_type_name'] = $orderinfo['pay_type_name'];
        $order['order_at'] = $orderinfo['order_at'];
        $data['orderinfo'] = $order;
        // 门店信息
        $data['storeinfo'] = $info['storeinfo'];
        // 导购信息
        $data['shoppingaccountinfo1'] = $info['shoppingaccountinfo1'];


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $data]]);
    }

}
